package com.jbwz.web.cms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jbwz.web.cms.common.viewenum.StatusEnum;
import com.jbwz.web.cms.entity.GoodsCategory;
import com.jbwz.web.cms.entity.vo.GoodsCategoryVO;
import com.jbwz.web.cms.mapper.GoodsCategoryMapper;
import com.jbwz.web.cms.service.GoodsCategoryService;
import com.jbwz.web.common.base.BaseServiceImpl;
import com.jbwz.web.common.base.IBasePage;
import com.jbwz.web.common.exception.BusinessException;
import com.jbwz.web.common.res.ResponseCodeBase;
import com.jbwz.web.common.util.BeanUtilCommon;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * 服务实现类
 *
 * @author yyh
 * @since 2022-02-03 09:32:08
 */
@Service
public class GoodsCategoryServiceImpl extends BaseServiceImpl<GoodsCategoryMapper, GoodsCategory>
    implements GoodsCategoryService {

  @Override
  public List<GoodsCategory> listFind(GoodsCategoryVO vo) {
    QueryWrapper<GoodsCategory> query =
        queryWithCid()
            .eq(Objects.nonNull(vo.getStatus()), "status", vo.getStatus())
            .orderByAsc("sorted");
    return baseMapper.selectList(query);
  }

  /**
   * 修改排序
   *
   * @param vos
   */
  @Override
  public void updateSorted(List<GoodsCategoryVO> vos) {
    List<GoodsCategory> goodsCategories =
        vos.stream()
            .map(
                vo -> {
                  GoodsCategory goodsCategory = new GoodsCategory();
                  goodsCategory.setSorted(vo.getSorted());
                  goodsCategory.setId(vo.getId());
                  return goodsCategory;
                })
            .toList();
    this.updateBatchById(goodsCategories);
  }

  @Override
  public void saveOrUpdateVO(GoodsCategoryVO vo) {
    QueryWrapper<GoodsCategory> query = queryWithCid().eq("name", vo.getName());
    GoodsCategory e = baseMapper.selectOne(query);
    if (Objects.nonNull(e)) {
      if (Objects.isNull(vo.getId()) || !e.getId().equals(vo.getId())) {
        throw BusinessException.resMsg(
            ResponseCodeBase.dataExist.withMsg(vo.getName() + "-菜品类型已存在"));
      }
    }
    if (Objects.isNull(vo.getStatus())) {
      vo.setStatus(StatusEnum.ENABLE.code());
    }
    vo.setCompanyId(getCurrentCid());
    saveOrUpdate(toEntity(vo));
  }

  @Override
  public GoodsCategoryVO toVO(GoodsCategory e) {
    GoodsCategoryVO vo = BeanUtilCommon.copy(e, new GoodsCategoryVO());
    return vo;
  }

  public GoodsCategory toEntity(GoodsCategoryVO vo) {
    GoodsCategory e = BeanUtilCommon.copy(vo, new GoodsCategory());
    return e;
  }
}
